package admin

import (
	"fmt"
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/pkg/utils"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/nleeper/goment"
	"github.com/sirupsen/logrus"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// UploadImage 上传图片，可以上传到本地或者上传到oss
func UploadImage(c *gin.Context) {
	file, err := c.FormFile("file")
	data := make(map[string]interface{})

	if err != nil {
		response.Fail(c, 201, "上传图片出错了")
		return
	}
	filePath := ""
	if setting.Config.App.UploadOss {
		res, msg := uploadOss(file)
		if !res {
			response.Fail(c, 201, msg)
			return
		}
		filePath = msg
	} else {
		filePath, err = uploadLocal(c, file)
		if err != nil {
			response.Fail(c, 201, "上传图片出错了")
			return
		}
	}

	data["location"] = filePath

	// response.Success(c, data)
	c.JSON(http.StatusOK, data)
	return
}

// renameFileName 重命名文件名
func renameFileName(file *multipart.FileHeader) string {
	return utils.RandomString(16) + filepath.Ext(file.Filename)
}

func uploadLocal(c *gin.Context, file *multipart.FileHeader) (string, error) {
	g, _ := goment.New()
	dirName := fmt.Sprintf("public/uploads/article/%s/%s/", g.Format("YYYYMMDD"), model.CurrentUserID(c))

	// 如果没有path文件目录就创建一个
	if _, err := os.Stat(dirName); err != nil {
		if !os.IsExist(err) {
			err2 := os.MkdirAll(dirName, os.ModePerm)
			if err2 != nil {
				return "", err
			}

			logrus.Info("创建文件夹:" + dirName)
		}
	}

	filePath := dirName + renameFileName(file)

	// 上传到指定目录
	err := c.SaveUploadedFile(file, filePath)

	if err != nil {
		return "", err
	}
	return filePath, nil
}

func uploadOss(file *multipart.FileHeader) (bool, string) {
	fmt.Println(file.Header)
	fmt.Println(file.Header.Get("Content-Type"))
	var fileExt string
	fileExt = strings.Split(file.Header.Get("Content-Type"), "/")[1]
	allowExts := []string{"jpg", "png", "gif", "jpeg", "webp"}
	allowFlag := false
	for _, ext := range allowExts {
		if ext == fileExt {
			allowFlag = true
			break
		}
	}
	if !allowFlag {
		return false, "不允许的类型"
	}

	// 文件名称
	timeStamp := time.Now().Unix()
	// 文件key
	fileKey := fmt.Sprintf("article/%d%s", timeStamp, fileExt)

	src, err := file.Open()
	if err != nil {
		return false, "上传失败"
	}
	defer src.Close()

	res, err := utils.OssUpload(fileKey, src)
	if err != nil {
		return false, "上传失败"
	}
	return true, res
}
